package com.hj.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hj.dao.MenuMapper;
import com.hj.pojo.Menu;
import com.hj.pojo.MenuExample;
import com.hj.pojo.MenuExample.Criteria;
import com.hj.service.IMenuService;

@Service
public class MenuServiceImpl implements IMenuService {

	@Autowired
	MenuMapper menuMapper;
	
	Lock lock = new ReentrantLock();
	
	Map cache = new HashMap();
	
	@Override
	public PageInfo<Menu> list(Integer page, Integer size, Menu menu) {
		// TODO Auto-generated method stub
		PageHelper.startPage(page, size);
		MenuExample ex = new MenuExample();
		Criteria criteria = ex.createCriteria();
		List<Menu> list = menuMapper.selectByExample(ex);
		PageInfo<Menu> pageInfo = new PageInfo<>(list);
		return pageInfo;
	}

	@Override
	public void add(Menu menu) {
		// TODO Auto-generated method stub
		menuMapper.insertSelective(menu);
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub
		menuMapper.deleteByPrimaryKey(id);
	}

	@Override
	public void update(Menu menu) {
		// TODO Auto-generated method stub
		menuMapper.updateByPrimaryKeySelective(menu);
	}

	@Override
	public Menu findOne(Integer id) {
		// TODO Auto-generated method stub
		return menuMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public List<Menu> findAll(MenuExample ex) {
		
		List<Menu> list = (List<Menu>)cache.get("mlist");
		// 缓存中有就直接返回
		if (list != null) {
			return list;
		}
		
		List<Menu> dbList = null;
		try {
			lock.lock();
			list = (List<Menu>)cache.get("mlist");
			if (list != null) {
				return list;
			}
		
			dbList = menuMapper.selectByExample(ex);
			// 放入缓存
			cache.put("mlist", dbList);
		} finally {
			lock.unlock();
		}
		
		
		return dbList;
	}

}
